package com.juku2024.juku

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import androidx.appcompat.widget.SwitchCompat
import com.rabbit.videoplayer.tools.VideoPlayerSPUtil
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.model.*
import com.juku2024.juku.network.retrofit.OnRetrofitResultListener
import com.juku2024.juku.tools.*
import com.juku2024.juku.viewmodel.SettingViewModel
import com.wanban.download.WBDownloadUtils
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class SettingActivity : BaseActivity() {

    private lateinit var cbDownload: SwitchCompat
    private lateinit var saveDataRl: View
    private lateinit var layoutClean: View
    private lateinit var layoutUpdate: View
    private lateinit var layoutPlayerSetting: View
    private lateinit var tvSettingClean: TextView
    private lateinit var tvUpdateContent: TextView
    private lateinit var downloadPathTv: TextView
    private lateinit var playerSettingTv: TextView

    private var updateModel: UpdateModel? = null
    private val currentAppVersion by lazy { AppUtils.getVersionCode() }
    private val currentAppVersionName by lazy { AppUtils.getVersionName() }
    private val viewModel by lazy { getViewModel(SettingViewModel::class.java) }

    override fun getLayoutResId(): Int {
        return R.layout.activity_setting
    }

    override fun initView() {
        super.initView()
        cbDownload = findViewById(R.id.cbDownload)
        saveDataRl = findViewById(R.id.save_data_rl)
        layoutClean = findViewById(R.id.layoutClean)
        layoutUpdate = findViewById(R.id.layoutUpdate)
        layoutPlayerSetting = findViewById(R.id.layoutPlayerSetting)
        tvSettingClean = findViewById(R.id.tvSettingClean)
        tvUpdateContent = findViewById(R.id.tvUpdateContent)
        downloadPathTv = findViewById(R.id.download_path_tv)
        playerSettingTv = findViewById(R.id.player_setting_tv)
    }

    override fun bindEvent() {
        super.bindEvent()
        // 设置是否允许流量下载
        cbDownload.setOnCheckedChangeListener { _, isChecked ->
            WBDownloadUtils.setDownloadOnlyWifi(!isChecked)
        }


        // 设置下载存储路径
        saveDataRl.setOnClickListener {
            val intent = Intent(this, PathActivity::class.java)
            startActivity(intent)
        }

        // 清空缓存
        layoutClean.setOnClickListener {
            val path = externalCacheDir?.absolutePath
            LogC.e("缓存目录 -> 删除文件目录 -> $path")
            externalCacheDir?.listFiles()?.forEach {
                val isDeleteSuccess = it.deleteRecursively()
                LogC.e("缓存目录 -> 删除文件目录 -> $isDeleteSuccess")
            }
            tvSettingClean.text = "0M"
            AppUtils.clearCache()
        }

        // 更新
        layoutUpdate.setOnClickListener {
            if (BaseApplication.isLimited) {
                setLatestVersionStyle()
                AlertUtils.alert("已是最新版本！")
                return@setOnClickListener
            }
            // 已请求过接口
            if (updateModel != null) {
                val latestNetAppVersion = updateModel?.versionNumber ?: -1
                if (latestNetAppVersion > currentAppVersion) {
                    setNeedUpdateStyle()
                    val typeStr = if (updateModel?.type == 0) "弹窗" else "页面"
                    AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE, AnalysisConstants.KEY_SHOW_DIALOG, "设置 -> $typeStr")
                    if (updateModel?.type == 0) { // 弹窗
                        showUpgradeDialog(updateModel)
                    } else { // 页面
                        val intent = Intent(this@SettingActivity, UpgradeActivity::class.java)
                        intent.putExtra(com.juku2024.juku.tools.Constants.INTENT_KEY_UPDATE,updateModel)
                        startActivity(intent)
                    }
                } else {
                    setLatestVersionStyle()
                    AlertUtils.alert("已是最新版本！")
                }
                return@setOnClickListener
            }

            doHttpUpdate()
        }

        layoutPlayerSetting.setOnClickListener {
            val intent = Intent(this, PlayerDecodeActivity::class.java)
            startActivity(intent)
        }
    }


    override fun init(savedInstanceState: Bundle?) {
        downloadPathTv.text = if (WBDownloadUtils.isUseSdcardDownload()) {
            getString(R.string.sd_store)
        } else {
            getString(R.string.phone_store)
        }

        // 设置缓存垃圾大小
        tvSettingClean.text = AppUtils.getCacheMemory()

        // 设置是否允许流量下载
        cbDownload.isChecked = !WBDownloadUtils.isDownloadOnlyWifi()

        // 受限制不检查升级
        if (BaseApplication.isLimited) {
            setLatestVersionStyle()
            return
        }
        // 请求一次升级
        val latestNetAppVersion = SPUtil.instance.latestNetAppVersion
        // 需要请求一次接口
        if (latestNetAppVersion <= -1) {
            // 先设置成需要更新
            setNeedUpdateStyle()
            doHttpUpdate()
        } else {
            val isNeedUpdate = latestNetAppVersion > currentAppVersion
            if (isNeedUpdate) { // 无需升级
                setNeedUpdateStyle()
            } else {
                setLatestVersionStyle()
            }
        }

        playerSettingTv.text = if (VideoPlayerSPUtil.instance.isEnableHardDecoder) {
            "硬解"
        } else {
            "软解"
        }

    }

    private fun setLatestVersionStyle() {
        tvUpdateContent.text = "无更新，当前版本:$currentAppVersionName"
        tvUpdateContent.setBackgroundResource(R.drawable.shape_me_need_upgrade)
    }

    private fun setNeedUpdateStyle() {
        tvUpdateContent.text = "有最新，当前版本:$currentAppVersionName"
        tvUpdateContent.setBackgroundResource(R.drawable.shape_hot_search_tag)
    }


    private fun doHttpUpdate() {
        showLoadingDialog()
        viewModel.doHttpUpgrade(object : OnRetrofitResultListener<UpgradeResponse> {
            override fun onSuccess(t: UpgradeResponse) {
                if (isActivityNotActive()) return
                hideLoadingDialog()
                updateModel = t.data
                if (t.data == null) {
                    AlertUtils.alert("已是最新版本！")
                    setLatestVersionStyle()
                    return
                }

                val latestNetAppVersion = t.data?.versionNumber ?: -1
                SPUtil.instance.latestNetAppVersion = latestNetAppVersion

                if (latestNetAppVersion > currentAppVersion) {
                    setNeedUpdateStyle()
//                    showUpgradeDialog(t.data)


                    val typeStr = if (t.data?.type == 0) "弹窗" else "页面"
                    AnalysisUtils.analysis(AnalysisConstants.EVENT_UPGRADE, AnalysisConstants.KEY_SHOW_DIALOG, "设置 -> $typeStr")
                    if (t.data?.type == 0) { // 弹窗
                        showUpgradeDialog(updateModel)
                    } else { // 页面
                        val intent = Intent(this@SettingActivity, UpgradeActivity::class.java)
                        intent.putExtra(com.juku2024.juku.tools.Constants.INTENT_KEY_UPDATE,updateModel)
                        startActivity(intent)
                    }
                } else {
                    setLatestVersionStyle()
                    AlertUtils.alert("已是最新版本！")
                }
            }

            override fun onFailed(msg: String) {
                if (isActivityNotActive()) return
                hideLoadingDialog()
                setLatestVersionStyle()
                AlertUtils.alert("已是最新版本！")
            }
        })
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun downloadPathEvent(event: DownloadPathEvent) {
        LogC.e(event)
        initDownloadPath()
    }

    private fun initDownloadPath() {
        saveDataRl.visibility = View.VISIBLE
        if (!WBDownloadUtils.isUseSdcardDownload()) {
            downloadPathTv.text = getString(R.string.phone_store)
        } else {
            downloadPathTv.text = getString(R.string.sd_store)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onChangePlayerDecoder(event: PlayerDecodeEvent){
        playerSettingTv.text = if (event.isPlayerDecoderHard) {
            "硬解"
        } else {
            "软解"
        }
    }
}